<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="card-title">
        <span>充值</span>
      </div>
      <div class="recharge-box">
        <span class="select-title">请选择银行</span>
        <!-- 银行图片的容器 -->
        <div class="bank-box">
          <!-- class的意思是 -->
          <div
            v-for="index of 4"
            :key="index"
            @click="selected(index)"
            :class="{ selectedstyle: index == rechargeForm.selectedIndex }"
          >
            <el-image :src="require(`@/assets/bank/${index}.png`)"></el-image>
          </div>
        </div>
        <el-divider></el-divider>
      </div>
      <div class="bottom">
        <el-form
          :model="rechargeForm"
          :rules="rules"
          ref="rechargeForm"
          label-width="80px"
          class="demo-rechargeForm"
        >
          <el-form-item prop="selectedIndex" class="selected-item">
          </el-form-item>
          <el-form-item label="可用金额:">
            <span>{{ this.accountInfo.balance }} 元</span>
          </el-form-item>

          <el-form-item label="充值金额:" prop="amount">
            <el-input-number
              :controls="false"     
              v-model="rechargeForm.amount"
              :min="1"
              :max="100"
            ></el-input-number>
          </el-form-item>

          <el-form-item prop="pass">
            <div class="identify-box" @click="makeCode">
              <SIdentify :identifyCode="identifycode"></SIdentify>
            </div>
          </el-form-item>

          <el-form-item label="验证码:" prop="verifycode">
            <el-input v-model="rechargeForm.verifycode"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('rechargeForm')"
              >充值</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { authRealNameAndPWS } from "@/utils/auth";
import { mapGetters, mapActions } from "vuex";
import SIdentify from "@/components/Identify/SIdentify.vue";
export default {
  // 注册组件才能在页面上使用
  components: {
    SIdentify,
  },
  data() {
    // 验证码的校验
    var validateverifycode = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入验证码"));
      } else if (value != this.identifycode) {
        console.log(value, this.identifycode);
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };
    // 金额验证
    var checkamount = (rule, value, callback) => {
      console.log(value)
      if (value == "") {
        callback(new Error("请输入金额"));
      } else if (value >= 100000) {
        this.rechargeForm.amount = 1
        callback(new Error("金额不能大于10万"));
      } else {
        callback();
      }
    };
    return {
      rechargeForm: {
        // 金额充值
        amount: "",
        // 验证码
        verifycode: "",
        // 当前选择银行索引
        selectedIndex: "",
      },
      // 校验规则
      rules: {
        selectedIndex: [
          { required: true, trigger: "change", message: "请选择银行" },
        ],
        verifycode: [{ validator: validateverifycode, trigger: "blur" }],
        amount: [{ validator: checkamount, trigger: "blur" }],
      },
      // 生成随机数
      identifycode: "",
      identifycodes: "0123456789",
    };
  },
  computed: {
    ...mapGetters(["accountInfo"]),
  },
  // 页面创建的时候应该做什么
  mounted() {
    authRealNameAndPWS(this, "realNameAuth");
    this.makeCode();
    console.log("在创建页面的时候的四位数是", this.identifycode);
  },
  methods: {
    ...mapActions({
      recharge: "assetManage/recharge",
      getInfo: "user/getInfo",
    }),
    // 点击银行图片
    selected(index) {
      if (index == this.rechargeForm.selectedIndex) {
        // 假如传进来的索引和已经记录的索引相同，就取消记录的索引
        this.rechargeForm.selectedIndex = ""; // 就是如果你点击了2次相同的银行的话，就会取消选择
      } else {
        // 如果和记录的索引不相同，就记录当前传入的索引
        this.rechargeForm.selectedIndex = index;
        this.$refs.rechargeForm.clearValidate("selectedIndex"); // 清除校验
      }
    },
    readomNum(max) {
      // Math.floor向下取整数，Math.random()生成0到1之间的随机数，包含0，但不包含1
      return Math.floor(Math.random() * max);
    },
    // 生成验证码图片（4位随机数字）
    makeCode() {
      this.identifycode = "";
      for (let index = 0; index < 4; index++) {
        this.identifycode +=
          this.identifycodes[this.readomNum(this.identifycodes.length)];
      }
      console.log(this.identifycode);
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("123");
          console.log(this.rechargeForm);
          this.recharge(this.rechargeForm).then((res) => {
            this.$message({
              message: "充值成功",
              type: "success",
            });
            // 重置表单
            this.onCancel("rechargeForm");
            // 刷新验证码
            this.makeCode();
            // 刷新用户信息
            this.getInfo();
          });
        } else {
          alert("error");
          return false;
        }
      });
    },
    // 重置表单
    onCancel(formname) {
      // restFields对整个表单进行进行重置
      this.$refs[formname].resetFields();
      // 重置金额
      this.rechargeForm.amount = 1;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  .card-title {
    font-size: 22px;
  }
  .bank-box {
    display: flex; // 横向的铺开
    .el-image {
      border: 1px solid rgb(226, 226, 226);
      margin: 8px 9px;
    }
  }
  .el-input {
    max-width: 200px;
  }
  .selectedstyle {
    .el-image {
      border: 2px solid rgb(28, 104, 167);
    }
  }
  .selected-item {
    position: relative;
    top: -50px;
  }
}
</style>